package com.just.springmvc4.filter;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;

/**
 * Created by han.yuan
 * 2018/5/28
 * 继承HttpServletRequestWrapper，截获数据流
 * 这玩意采用了装饰者模式
 * 通过这里还可以对HttpServletRequest参数进行修改
 */
public class PayloadRequestWrapper extends HttpServletRequestWrapper{
    private final String body;
    public PayloadRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        if(null != request.getContentType() && request.getContentType().contains("multipart/form-data")){
            body=null;
            return;
        }
        final StringBuilder bodyBuilder = new StringBuilder();

        BufferedReader bufferedReader = null;

        try (InputStream inputStream = request.getInputStream()) {

            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    bodyBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }

        body = bodyBuilder.toString();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes(Charset.forName("utf-8")));


        try (ServletInputStream servletInputStream = new ServletInputStream() {

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return true;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                throw new UnsupportedOperationException();
            }

        }) {
            return servletInputStream;
        }
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public String getBody() {
        return body;
    }
}
